package com.mumu.quratz.util;


import com.mumu.quratz.constant.ScheduleConstants;
import com.mumu.quratz.entity.SimpleProperty;
import com.mumu.quratz.entity.SysJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.util.Objects;

import static org.quartz.TriggerBuilder.newTrigger;

/**
 * 定时任务工具类
 *
 * @author mumu
 */
@Slf4j
public class ScheduleUtils {

    /**
     * 创建简单的调度器
     *
     * @param scheduler spring注入即可
     * @param job       公共任务类 需要传入  jobId  jobName  targetClass
     * @param object    业务map类
     * @throws SchedulerException
     */
    public static void createExtractTopicScheduleJob(Scheduler scheduler, SysJob job, Object object) throws SchedulerException {
        SimpleProperty simpleProperty = job.getSimpleProperty();
        if (Objects.isNull(simpleProperty)) {
            return;
        }

        String targetClass = job.getTargetClass();
        Job jobClass = (Job) SpringContextUtils.getBean(targetClass);
        // 构建job信息
        String jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(jobClass.getClass()).withIdentity(getJobKey(jobId, jobGroup)).build();

        DailyTimeIntervalScheduleBuilder scheduleBuilder = DailyTimeIntervalScheduleBuilder
                .dailyTimeIntervalSchedule()
                .startingDailyAt(simpleProperty.getTimeOfDay())
                .withRepeatCount(Math.toIntExact(simpleProperty.getRepeatCount()))
                .withMisfireHandlingInstructionIgnoreMisfires()
                //.withIntervalInHours(simpleProperty.getIntervalInHours());
                .withIntervalInSeconds(simpleProperty.getIntervalInSeconds());

        DailyTimeIntervalTrigger trigger = TriggerBuilder.newTrigger()
                .startAt(simpleProperty.getStartTime())
                .withSchedule(scheduleBuilder)
                .build();

        // 放入任务对象，运行时的方法可以获取
        jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, object);

        // 判断是否存在
        if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(jobId, jobGroup));
        }

        scheduler.scheduleJob(jobDetail, trigger);
        log.info("定时任务创建完成");
    }


    public static void createVideoTopicScheduleJob(Scheduler scheduler, SysJob job, Object object) throws SchedulerException {
        SimpleProperty simpleProperty = job.getSimpleProperty();
        if (Objects.isNull(simpleProperty)) {
            return;
        }

        String targetClass = job.getTargetClass();
        Job jobClass = (Job) SpringContextUtils.getBean(targetClass);
        // 构建job信息
        String jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(jobClass.getClass()).withIdentity(getJobKey(jobId, jobGroup)).build();

        Trigger trigger = newTrigger()
                .startAt(simpleProperty.getStartTime())
                .build();

        // 放入任务对象，运行时的方法可以获取
        jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, object);

        // 判断是否存在
        if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(jobId, jobGroup));
        }

        scheduler.scheduleJob(jobDetail, trigger);
    }


    public static JobKey getJobKey(String jobId, String jobGroup) {
        return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
    }

    public static TriggerKey getTriggerKey(String jobId, String jobGroup) {
        return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup);
    }

    /**
     * 设置定时任务策略
     */
    public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
            throws RuntimeException {
        switch (job.getMisfirePolicy()) {
            case ScheduleConstants.MISFIRE_DEFAULT:
                return cb;
            case ScheduleConstants.MISFIRE_IGNORE_MISFIRES:
                return cb.withMisfireHandlingInstructionIgnoreMisfires();
            case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED:
                return cb.withMisfireHandlingInstructionFireAndProceed();
            case ScheduleConstants.MISFIRE_DO_NOTHING:
                return cb.withMisfireHandlingInstructionDoNothing();
            default:
                throw new RuntimeException("The task misfire policy '" + job.getMisfirePolicy()
                        + "' cannot be used in cron schedule tasks");
        }
    }


}
